//
//  InviteFriendsViewController.m
//  Article
//
//  Created by Haricot_cpc17 on 16/4/22.
//  Copyright © 2016年 mac. All rights reserved.
//
//邀请好友
#import "InviteFriendsViewController.h"
#import <WXApi.h>

@interface InviteFriendsViewController (){
    UIImageView *_imageView;
    UIButton *_cancelbtn;//取消分享
    UIView   *_sheraview;//分享
    UIButton *_rightbtn;
    UIActivityIndicatorView *_indicatorView;
    
}



@end

@implementation InviteFriendsViewController

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    self.tabBarController.tabBar.hidden = YES;
    self.tabBarController.tabBar.translucent = YES;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.navigationItem.title = @"推广二维码";
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"arrow"] style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
    
    
    _rightbtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 40, 40)];
    _rightbtn.titleLabel.font = [UIFont fontWithName:@"Heiti SC" size:15];
    [_rightbtn setTitle:@"分享" forState:UIControlStateNormal];
    [_rightbtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_rightbtn addTarget:self action:@selector(getMessage) forControlEvents:UIControlEventTouchUpInside];
    
    
    UIBarButtonItem *right = [[UIBarButtonItem alloc]initWithCustomView:_rightbtn];
    self.navigationItem.rightBarButtonItem = right;
    //[self.navigationItem.rightBarButtonItem setTintColor:UIColorFromRGB(0x444444)];
    
    self.view.backgroundColor =  UIColorFromRGB(0xA4D0FF);
    
    [self createimage];
    
    [self createView];
    
    //[self createQRCode];
    
}

-(void)createView{
//    
//    UIImageView *headimage = [[UIImageView alloc]initWithFrame:CGRectMake(10 , 10, WIDTH/6, WIDTH/6)];
//    headimage.layer.masksToBounds = YES;
//    headimage.layer.cornerRadius = WIDTH/12;
//    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
//    [headimage sd_setImageWithURL:[NSURL URLWithString:[user objectForKey:@"imageurl"]]];
//    [self.view addSubview:headimage];
    
    
//    UILabel *titlelab = [[UILabel alloc]initWithFrame:CGRectMake(WIDTH/6+20,10,WIDTH-WIDTH/6-20,60)];
//    titlelab.text = [NSString stringWithFormat:@"我是%@，\r快加入我的团队吧~",[user objectForKey:@"nickname"]];
//    titlelab.textAlignment = NSTextAlignmentLeft;
//    titlelab.numberOfLines = 0;
//    titlelab.textColor = UIColorFromRGB(0x333333);
//    titlelab.font = [UIFont fontWithName:@"Heiti SC-Bold" size:12 * MYWIDTH];
//    [self.view addSubview:titlelab];
}




- (void)getMessage{
    _rightbtn.userInteractionEnabled = NO;
    _cancelbtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, WIDTH , HEIGHT)];
    
    _cancelbtn.alpha = 0;
    _cancelbtn.backgroundColor = [UIColor blackColor];
    
    [_cancelbtn addTarget:self action:@selector(removeView) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_cancelbtn];
    
    
    [UIView animateWithDuration:0.3 animations:^{
        
        
        
        _cancelbtn.alpha = 0.6;
        
        _sheraview = [[UIView alloc]initWithFrame:CGRectMake(0, HEIGHT - 180 * MYWIDTH, WIDTH, 180 * MYWIDTH)];
        _sheraview.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:_sheraview];
        
        UILabel *titlelab = [[UILabel alloc]initWithFrame:CGRectMake(5, 5, WIDTH/2, 20)];
        titlelab.text = @"分享到";
        titlelab.textColor = UIColorFromRGB(0x333333);
        titlelab.font = [UIFont systemFontOfSize:16];
        [_sheraview addSubview:titlelab];
        
        
        UIButton *wxbtn = [[UIButton alloc]initWithFrame:CGRectMake(15, 35 * MYWIDTH, 50 * MYWIDTH, 50 * MYWIDTH)];
        wxbtn.tag = 1;
        [wxbtn setBackgroundImage:[UIImage imageNamed:@"weixin"] forState:UIControlStateNormal];
        [wxbtn addTarget:self action:@selector(sheraMessage:) forControlEvents:UIControlEventTouchUpInside];
        [_sheraview addSubview:wxbtn];
        
        UIButton *pyqbtn = [[UIButton alloc]initWithFrame:CGRectMake(90 * MYWIDTH, 35 * MYWIDTH, 50 * MYWIDTH, 50 * MYWIDTH)];
        pyqbtn.tag = 2;
        [pyqbtn setBackgroundImage:[UIImage imageNamed:@"pengyouquan"] forState:UIControlStateNormal];
        [pyqbtn addTarget:self action:@selector(sheraMessage:) forControlEvents:UIControlEventTouchUpInside];
        [_sheraview addSubview:pyqbtn];
        
        UILabel *wxlab = [[UILabel alloc]initWithFrame:CGRectMake(5, 85 * MYWIDTH, 70 * MYWIDTH, 20 * MYWIDTH)];
        wxlab.text = @"微信好友";
        wxlab.font = [UIFont systemFontOfSize:11];
        wxlab.textAlignment = NSTextAlignmentCenter;
        wxlab.textColor = UIColorFromRGB(0x666666);
        [_sheraview addSubview:wxlab];
        
        UILabel *pyqlab = [[UILabel alloc]initWithFrame:CGRectMake(80 * MYWIDTH, 85 * MYWIDTH, 70 * MYWIDTH, 20 * MYWIDTH)];
        pyqlab.text = @"朋友圈";
        pyqlab.font = [UIFont systemFontOfSize:12];
        pyqlab.textAlignment = NSTextAlignmentCenter;
        pyqlab.textColor = UIColorFromRGB(0x666666);
        [_sheraview addSubview:pyqlab];
        
        [WXApi registerApp:@"wx24f1f8198ba7b121"];
        
    }];
    
}
-(void)sheraMessage:(UIButton *)btn{
    
    [self removeView];
    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    
    
    NSDictionary *dic = @{@"link":[user objectForKey:@"uid"]};
    
    AFHTTPRequestOperationManager *manager = [MyTools initAFHttpManager];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    [manager POST:SHARE_PAGE_URL parameters:dic success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        if ([[responseObject objectForKey:@"status"] intValue] == 1) {
            
            WXMediaMessage *messgae = [WXMediaMessage message];
            messgae.title = [[responseObject objectForKey:@"data"] objectForKey:@"title"];
            [messgae setThumbImage:[self getImageFromURL:[[responseObject objectForKey:@"data"] objectForKey:@"logo"]]];
            messgae.description = [[responseObject objectForKey:@"data"] objectForKey:@"des"];
            WXWebpageObject *webpage = [WXWebpageObject object];
            webpage.webpageUrl = [NSString stringWithFormat:@"http://wz.ijiaque.com/app/share/share_form.html?link=%@",[user objectForKey:@"uid"]];
            
            messgae.mediaObject = webpage;
            
            SendMessageToWXReq *req = [[SendMessageToWXReq alloc]init];
            req.bText = NO;
            req.message = messgae;
            
            if (btn.tag == 1) {
                req.scene = WXSceneSession;
            }else if (btn.tag == 2){
                req.scene = WXSceneTimeline;
            }
            
            [WXApi sendReq:req];
            
        }else{
            [self.view makeToast:[responseObject objectForKey:@"info"] duration:1.0 position:CSToastPositionCenter];
        }
        
    } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        
        if ([MyTools connectedToNetwork] == 0) {
            [self.view makeToast:@"请检查是否联网" duration:1.0 position:CSToastPositionCenter];
        }else{
            [self.view makeToast:@"服务器错误，再试一次" duration:1.0 position:CSToastPositionCenter];
        }
    }];
    
}
-(UIImage *) getImageFromURL:(NSString *)fileURL {
    //NSLog(@"执行图片下载函数");
    UIImage * result;
    NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:fileURL]];
    result = [UIImage imageWithData:data];
    return result;
}
-(void)removeView{
    _rightbtn.userInteractionEnabled = YES;
    [UIView animateWithDuration:0.5 animations:^{
        [_cancelbtn removeFromSuperview];
        [_sheraview removeFromSuperview];
    }];
}




#pragma mark 二维码
-(void)createimage{
    UIImageView *backimage = [[UIImageView alloc]initWithFrame:CGRectMake(0,-64 * MYHEIGHT, WIDTH, HEIGHT)];
    backimage.image = [UIImage imageNamed:@"倍增店分享"];
    [self.view addSubview:backimage];
    
    //    UILabel *fenlab = [[UILabel alloc]initWithFrame:CGRectMake(20, HEIGHT/4*3, WIDTH, 20)];
    //    fenlab.text = @"快来分享，寻找你的专属团队成员吧!";
    //    fenlab.font = [UIFont systemFontOfSize:13];
    //    fenlab.textAlignment = NSTextAlignmentCenter;
    //    fenlab.textColor = UIColorFromRGB(0xffffff);
    //    [backimage addSubview:fenlab];
    
    //    UILabel *saolab = [[UILabel alloc]initWithFrame:CGRectMake(WIDTH/3*2-15, HEIGHT/8*7, WIDTH/3, 20)];
    //    saolab.text = @"立即成为我的成员";
    //    saolab.font = [UIFont systemFontOfSize:13];
    //    //saolab.textAlignment = NSTextAlignmentCenter;
    //    saolab.textColor = UIColorFromRGB(0xffffff);
    //    [backimage addSubview:saolab];
    
//    UILabel *zhulab = [[UILabel alloc]initWithFrame:CGRectMake(WIDTH/2 -WIDTH/4, WIDTH/6 + 30 * MYWIDTH + WIDTH/2, WIDTH/2, 15)];
//    zhulab.text = @"长按二维码保存到本地";
//    zhulab.font = [UIFont systemFontOfSize:11];
//    zhulab.textAlignment = NSTextAlignmentCenter;
//    zhulab.textColor = UIColorFromRGB(0x666666);
//    [self.view addSubview:zhulab];
    
    //二维码
    _imageView =[[UIImageView alloc]initWithFrame:CGRectMake(WIDTH/2 - WIDTH/6 * MYHEIGHT ,WIDTH/6+10 , WIDTH/3 * MYHEIGHT, WIDTH/3 * MYHEIGHT)];
    //_imageView.backgroundColor =[UIColor blackColor];
    
    [self.view addSubview:_imageView];
    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    
    UIImage *qrcode = [self createNonInterpolatedUIImageFormCIImage:[self createQRForString:[NSString stringWithFormat:@"http://wz.ijiaque.com/app/share/share_form.html?link=%@",[user objectForKey:@"uid"]]] withSize:250.0f];
    
    UIImage *customQrcode = [self imageBlackToTransparent:qrcode withRed:0 andGreen:0 andBlue:0];
    
    _imageView.image = customQrcode;
    _imageView.layer.shadowOffset = CGSizeMake(0, 2);
    _imageView.layer.shadowRadius = 2;
    _imageView.layer.shadowColor = [UIColor blackColor].CGColor;
    _imageView.layer.shadowOpacity = 0;
    _imageView.userInteractionEnabled = YES;
    
    UILongPressGestureRecognizer *singleTap = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(photoClick:)];
    [_imageView addGestureRecognizer:singleTap];//点击图片事件
    
    
}
//长按保存二维码
-(void)photoClick:(UILongPressGestureRecognizer *)gesture {
    if(gesture.state == UIGestureRecognizerStateBegan)
    {
        UIImageWriteToSavedPhotosAlbum(_imageView.image, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
        
        UIActivityIndicatorView *indicator = [[UIActivityIndicatorView alloc] init];
        indicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
        //indicator.center = self.center;
        _indicatorView = indicator;
        [[UIApplication sharedApplication].keyWindow addSubview:indicator];
        [indicator startAnimating];
    }
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo;
{
    [_indicatorView removeFromSuperview];
    
    if (error) {
        [self.view makeToast:@"二维码保存失败" duration:0.5 position:CSToastPositionCenter];
    }   else {
        [self.view makeToast:@"二维码保存成功" duration:0.5 position:CSToastPositionCenter];
    }
}

- (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat) size {
    CGRect extent = CGRectIntegral(image.extent);
    CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
    // create a bitmap image that we'll draw into a bitmap context at the desired size;
    size_t width = CGRectGetWidth(extent) * scale;
    size_t height = CGRectGetHeight(extent) * scale;
    CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
    CIContext *context = [CIContext contextWithOptions:nil];
    CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    CGContextScaleCTM(bitmapRef, scale, scale);
    CGContextDrawImage(bitmapRef, extent, bitmapImage);
    // Create an image with the contents of our bitmap
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    // Cleanup
    CGContextRelease(bitmapRef);
    CGImageRelease(bitmapImage);
    return [UIImage imageWithCGImage:scaledImage];
}

- (CIImage *)createQRForString:(NSString *)qrString {
    // Need to convert the string to a UTF-8 encoded NSData object
    NSData *stringData = [qrString dataUsingEncoding:NSUTF8StringEncoding];
    // Create the filter
    CIFilter *qrFilter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    // Set the message content and error-correction level
    [qrFilter setValue:stringData forKey:@"inputMessage"];
    [qrFilter setValue:@"M" forKey:@"inputCorrectionLevel"];
    // Send the image back
    return qrFilter.outputImage;
}

void ProviderReleaseData (void *info, const void *data, size_t size){
    free((void*)data);
}
- (UIImage*)imageBlackToTransparent:(UIImage*)image withRed:(CGFloat)red andGreen:(CGFloat)green andBlue:(CGFloat)blue{
    const int imageWidth = image.size.width;
    const int imageHeight = image.size.height;
    size_t      bytesPerRow = imageWidth * 4;
    uint32_t* rgbImageBuf = (uint32_t*)malloc(bytesPerRow * imageHeight);
    // create context
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate(rgbImageBuf, imageWidth, imageHeight, 8, bytesPerRow, colorSpace,
                                                 kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipLast);
    CGContextDrawImage(context, CGRectMake(0, 0, imageWidth, imageHeight), image.CGImage);
    // traverse pixe
    int pixelNum = imageWidth * imageHeight;
    uint32_t* pCurPtr = rgbImageBuf;
    for (int i = 0; i < pixelNum; i++, pCurPtr++){
        if ((*pCurPtr & 0xFFFFFF00) < 0x99999900){
            // change color
            uint8_t* ptr = (uint8_t*)pCurPtr;
            ptr[3] = red; //0~255
            ptr[2] = green;
            ptr[1] = blue;
        }else{
            uint8_t* ptr = (uint8_t*)pCurPtr;
            ptr[0] = 0;
        }
    }
    // context to image
    CGDataProviderRef dataProvider = CGDataProviderCreateWithData(NULL, rgbImageBuf, bytesPerRow * imageHeight, ProviderReleaseData);
    CGImageRef imageRef = CGImageCreate(imageWidth, imageHeight, 8, 32, bytesPerRow, colorSpace,
                                        kCGImageAlphaLast | kCGBitmapByteOrder32Little, dataProvider,
                                        NULL, true, kCGRenderingIntentDefault);
    CGDataProviderRelease(dataProvider);
    UIImage* resultUIImage = [UIImage imageWithCGImage:imageRef];
    // release
    CGImageRelease(imageRef);
    CGContextRelease(context);
    CGColorSpaceRelease(colorSpace);
    return resultUIImage;
}



-(void)back{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end

//#pragma mark 原生二维码生成
//- (void)createQRCode {
//
//    // 创建过滤器
//    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
//
//    // 恢复默认
//    [filter setDefaults];
//
//    // 给过滤器添加数据
//
//    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
//
//
//
//    NSString *dataString = [NSString stringWithFormat:@"%@",[user objectForKey:@"mobile"]];
//
//    NSData *data = [dataString dataUsingEncoding:NSUTF8StringEncoding];
//    [filter setValue:data forKey:@"inputMessage"];
//
//    // 获取输出的二维码
//    CIImage *outputImage = [filter outputImage];
//
//
//    // 获取高清的二维码 200 * 200
//    _image = [self createNonInterpolatedUIImageFormCIImage:outputImage withSize:200.0];
//    _imageView.image = _image;
//    NSLog(@"%@",dataString);
//    // 添加logo
//    CALayer *logoLayer = [CALayer layer];
//
//    logoLayer.frame = CGRectMake(105, 100, 50, 50);
//
//
//    //logoLayer.contents = (__bridge id)[UIImage imageNamed:@"头像"].CGImage;
//
//    [_imageView.layer addSublayer:logoLayer];
//
//}
//- (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat)size {
//    CGRect extent = CGRectIntegral(image.extent);
//    CGFloat scale = MIN(size / CGRectGetWidth(extent), size / CGRectGetHeight(extent));
//
//    // 1.创建bitmap;
//    size_t width = CGRectGetWidth(extent) * scale;
//    size_t height = CGRectGetHeight(extent) * scale;
//    CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
//    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
//    CIContext *context = [CIContext contextWithOptions:nil];
//    CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
//    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
//    CGContextScaleCTM(bitmapRef, scale, scale);
//    CGContextDrawImage(bitmapRef, extent, bitmapImage);
//
//    // 2.保存bitmap到图片
//    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
//    CGContextRelease(bitmapRef);
//    CGImageRelease(bitmapImage);
//    return [UIImage imageWithCGImage:scaledImage];
//}